package com.crm.service;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.crm.dao.IncomeDAO;
import com.crm.po.Income;
import com.crm.util.DateEx;
import com.crm.util.ExcelEx;
import com.crm.util.MathEx;
import com.crm.util.RequestEx;
import com.crm.util.StringEx;
import com.crm.vo.Excel;

public class IncomeService {
	
	private static Logger logger = Logger.getLogger(IncomeService.class);
	
	public Map<String, Object> getIncomes(HttpServletRequest request){
		StringBuffer Hql = new StringBuffer(" from Income t where 1=1 ");
		int page = Integer.parseInt(request.getParameter("page"));//当前第几页
		int rows = Integer.parseInt(request.getParameter("rows"));//每页显示几行

		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String fpnumber = RequestEx.getStringTrim(request.getParameter("fpnumber"));
		String ddnumber = RequestEx.getStringTrim(request.getParameter("ddnumber"));
		String qsr = RequestEx.getStringTrim(request.getParameter("qsr"));
		String buyer = RequestEx.getStringTrim(request.getParameter("buyer"));

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(fpnumber != null && fpnumber.trim().length() > 0){
			Hql.append(" and t.fpnumber like '%");
			Hql.append(fpnumber);
			Hql.append("%' ");
		}
		if(ddnumber != null && ddnumber.trim().length() > 0){
			Hql.append(" and t.ddnumber like '%");
			Hql.append(ddnumber);
			Hql.append("%' ");
		}
		if(qsr != null && qsr.trim().length() > 0){
			Hql.append(" and t.qsr like '%");
			Hql.append(qsr);
			Hql.append("%' ");
		}
		if(buyer != null && buyer.trim().length() > 0){
			Hql.append(" and t.buyer like '%");
			Hql.append(buyer);
			Hql.append("%' ");
		}
		
		IncomeDAO dao = new IncomeDAO();
		String countHql = "select count(t.tid) " + Hql.toString();
		int count = dao.getCount(countHql);
		Hql.append(" order by t.kpdate desc, t.creattime desc  ");
	    List<Income> list = dao.incomeListPage(Hql.toString(), (page-1) * rows, rows);
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("count", count);
	    map.put("rows", list);
	    
	    return map;
	} 
	
	public int getIncomeCountByTreeid(String treeid, String islive){
		StringBuffer Hql = new StringBuffer(" from Income t where 1=1 ");

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		
		IncomeDAO dao = new IncomeDAO();
		String countHql = "select count(t.tid) " + Hql.toString();
		int count = dao.getCount(countHql);
	    
	    return count;
	} 
	
	public boolean saveOrUpdateIncome(HttpServletRequest request){
		try{
			
			String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
			
			String tid = RequestEx.getStringTrim(request.getParameter("tid"));
			
			Date kpdate = RequestEx.getSqlDate(request.getParameter("kpdate"));
			Double kpprice = RequestEx.getDouble(request.getParameter("kpprice"));
			Double dzprice = RequestEx.getDouble(request.getParameter("dzprice"));
			String fpnumber = RequestEx.getStringTrim(request.getParameter("fpnumber"));
			String ddnumber = RequestEx.getStringTrim(request.getParameter("ddnumber"));
			String qsr = RequestEx.getStringTrim(request.getParameter("qsr"));
			Date qsdate = RequestEx.getSqlDate(request.getParameter("qsdate"));
			String isdz = RequestEx.getStringTrim(request.getParameter("isdz"));
			String xm = RequestEx.getStringTrim(request.getParameter("xm"));
			String buyer = RequestEx.getStringTrim(request.getParameter("buyer"));
			Date dzdate = RequestEx.getSqlDate(request.getParameter("dzdate"));
			String remark = RequestEx.getStringTrim(request.getParameter("remark"));
			
			IncomeDAO dao = new IncomeDAO();
			Income income = null;
			if(tid != null && tid.trim().length() > 0){
				income = dao.findById(tid);
			}else{				
				income = new Income();
				income.setCreattime(DateEx.getCurDatetimeAsLong());
				income.setCreater(RequestEx.getCurUser(request).getUsername());
			}
			income.setKpdate(kpdate);
			income.setKpprice(kpprice);
			income.setDzprice(dzprice);
			income.setFpnumber(fpnumber);
			income.setDdnumber(ddnumber);
			income.setQsr(qsr);
			income.setQsdate(qsdate);
			income.setIsdz(isdz);
			income.setXm(xm);
			income.setBuyer(buyer);
			income.setDzdate(dzdate);

			income.setCGroup(treeid);
			income.setRemark(remark);
			income.setIslive("Y");
			
			income.setUpdatetime(DateEx.getCurDatetimeAsLong());
			income.setUpdater(RequestEx.getCurUser(request).getUsername());
			
			dao.saveOrUpdate(income);
		}catch(Exception e){
			logger.error("save or update income fail:", e);
			return false;
		}
	    return true;
	}
	
	public boolean updateDdnumber(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			String newDdnumber = RequestEx.getStringTrim(request.getParameter("newDdnumber"));
			if(tids.length() > 0){
				String hql = "UPDATE Income T SET T.ddnumber = '" + newDdnumber + "' WHERE T.tid IN (" + tids + ")";
				IncomeDAO dao = new IncomeDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete inventory fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean deleteIncomes(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "UPDATE Income T SET T.islive = 'N' WHERE T.tid IN (" + tids + ")";
				IncomeDAO dao = new IncomeDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete income fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean recoverIncomes(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "UPDATE Income T SET T.islive = 'Y' WHERE T.tid IN (" + tids + ")";
				IncomeDAO dao = new IncomeDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("recover income fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean reallyDeleteIncomes(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "DELETE FROM Income T WHERE T.tid IN (" + tids + ")";
				IncomeDAO dao = new IncomeDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("really delete income fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public double mathJJCC(HttpServletRequest request){
		int type = RequestEx.getInteger(request.getParameter("type"));
		Double number1 = RequestEx.getDouble(request.getParameter("n1"));
		Double number2 = RequestEx.getDouble(request.getParameter("n2"));
		
		return MathEx.mathJJCC(number1, number2, 2, type);
	}
	
	public String mathBatchAdd(HttpServletRequest request){			
		String kpprice_temp = RequestEx.getStringTrim(request.getParameter("kpprice_temp"));
		String dzprice_temp = RequestEx.getStringTrim(request.getParameter("dzprice_temp"));
		
		double kpprice_sum = MathEx.mathBatchAdd(kpprice_temp.split("_"), 2);
		double dzprice_sum = MathEx.mathBatchAdd(dzprice_temp.split("_"), 2);
		
		StringBuffer buffer = new StringBuffer("");
		
		buffer.append("{\"kpprice_sum\":\"" + kpprice_sum + "\",");
		buffer.append("\"dzprice_sum\":\"" + dzprice_sum + "\"}");

		return buffer.toString();
	}


	public void exportIncomes(HttpServletRequest request, HttpServletResponse response){
		StringBuffer Hql = new StringBuffer(" from Income t where 1=1 ");
		
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String tids = RequestEx.getStringTrim(request.getParameter("tids"));
		String fpnumber = RequestEx.getStringTrim(request.getParameter("fpnumber"));
		String ddnumber = RequestEx.getStringTrim(request.getParameter("ddnumber"));
		String qsr = RequestEx.getStringTrim(request.getParameter("qsr"));
		String buyer = RequestEx.getStringTrim(request.getParameter("buyer"));

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(tids != null && tids.trim().length() > 0){
			Hql.append(" and t.tid in (");
			Hql.append(tids);
			Hql.append(") ");
		}
		if(fpnumber != null && fpnumber.trim().length() > 0){
			Hql.append(" and t.fpnumber like '%");
			Hql.append(fpnumber);
			Hql.append("%' ");
		}
		if(ddnumber != null && ddnumber.trim().length() > 0){
			Hql.append(" and t.ddnumber like '%");
			Hql.append(ddnumber);
			Hql.append("%' ");
		}
		if(qsr != null && qsr.trim().length() > 0){
			Hql.append(" and t.qsr like '%");
			Hql.append(qsr);
			Hql.append("%' ");
		}
		if(buyer != null && buyer.trim().length() > 0){
			Hql.append(" and t.buyer like '%");
			Hql.append(buyer);
			Hql.append("%' ");
		}
		
		IncomeDAO dao = new IncomeDAO();
		Hql.append(" order by t.kpdate desc ");
	    List<Income> list = dao.incomeList(Hql.toString());
	    
	    String[][] grids = new String[list.size() + 1][14];
	    String[] titles = {"开票日期", "发票金额", "到账金额", "发票号", "订单号", "签收人", "签收日期", "到账情况", "项目", "采购人", "到账日期", "备注", "创建时间", "修改时间"}; 
	    grids[0] = titles;
		for(int i = 0; i < list.size(); i ++){
			Income income = list.get(i);
			grids[i + 1][0] = StringEx.valueOf(income.getKpdate());
			grids[i + 1][1] = StringEx.valueOf(income.getKpprice());
			grids[i + 1][2] = StringEx.valueOf(income.getDzprice());
			grids[i + 1][3] = StringEx.valueOf(income.getFpnumber());
			grids[i + 1][4] = StringEx.valueOf(income.getDdnumber());
			grids[i + 1][5] = StringEx.valueOf(income.getQsr());
			grids[i + 1][6] = StringEx.valueOf(income.getQsdate());
			grids[i + 1][7] = StringEx.valueOf(income.getIsdz());
			grids[i + 1][8] = StringEx.valueOf(income.getXm());
			grids[i + 1][9] = StringEx.valueOf(income.getBuyer());
			grids[i + 1][10] = StringEx.valueOf(income.getDzdate());
			grids[i + 1][11] = StringEx.valueOf(income.getRemark());
			grids[i + 1][12] = StringEx.valueOfLongDate(income.getCreattime());
			grids[i + 1][13] = StringEx.valueOfLongDate(income.getUpdatetime());
		}
	    ExcelEx.toExcel(request, response, new Excel("销售信息[导出时间" + DateEx.getCurDateTime() + "]", grids));
	} 
	
}
